//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;

namespace OpenLS.UI
{
    class SqueezePanel : Panel
    {
        public SqueezePanel()
        {
            IsItemsHost = true;
        }
        protected override Size MeasureOverride(Size availableSize)
        {
            //\\Debug.WriteLine("MeasureOverride " + GetType());
            double x = 0;
            double y = 0;
            foreach (UIElement element in InternalChildren)
            {
                element.Measure(availableSize);
                x += element.DesiredSize.Width + 4;
                y = Math.Max(element.DesiredSize.Height, y);
            }
            return new Size(Math.Min(x, availableSize.Width), y);
        }
        protected override Size ArrangeOverride(Size finalSize)
        {
            //\\ Debug.WriteLine("ArrangeOverride " + GetType());
            List<double> widths = new List<double>();
            foreach (UIElement element in InternalChildren)
            {
                widths.Add(element.DesiredSize.Width);
            }
            widths.Sort();
            List<double> acc = new List<double>();
            double sum = 0;
            for (int i = 0; i < widths.Count; i++)
            {
                sum += widths[i];
                acc.Add(sum);
            }
            double max = double.MaxValue;
            double maxWidth = finalSize.Width - 4 * widths.Count;
            if (acc.Count == 0)
                return base.ArrangeOverride(finalSize);
            if (acc[acc.Count - 1] <= finalSize.Width)
                max = double.MaxValue;
            else
            {
                for (int i = acc.Count - 1; i >= 0; i--)
                {
                    if (i == 0)
                    {
                        max = maxWidth / acc.Count;
                        break;
                    }
                    double totalWidth = acc[i - 1] + (acc.Count - i) * widths[i];
                    if (totalWidth < maxWidth)
                    {
                        max = (maxWidth - acc[i - 1]) / (acc.Count - i);
                        break;
                    }

                }
            }
            double x = 0;
            foreach (UIElement e in InternalChildren)
            {
                double w = Math.Min(e.DesiredSize.Width, max) + 4;
                e.Arrange(new Rect(x, 0, w, finalSize.Height));
                x += w;
            }
            return new Size(x, finalSize.Height);
        }

    }
}
